<template>
  <ScaleScreen :width="1920" :height="1080" class="scale-wrap">
    <div id="flow_man">
      <div style="width: 100%; height: 1080px; position: relative" id="screen">
        <div id="container"></div>
        <div id="stencil" ref="stencil" style="transition: all 1s"></div>
        <div style="position: absolute; left: -10px; z-index: 1; top: 49%">
          <el-button
            circle
            type="primary"
            @click="
              () => {
                this.btn = false;
                $refs.stencil.style.transform = 'translateX(-300px)';
              }
            "
            v-show="this.btn"
          >
            <!-- <CaretLeftIcon /> -->
          </el-button>
          <el-button
            circle
            type="primary"
            @click="
              () => {
                this.btn = true;
                $refs.stencil.style.transform = 'translateX(0px)';
              }
            "
            v-show="!this.btn"
          >
          </el-button>
        </div>
        <div id="screen-select" style="position: absolute; right: 2%; top: 3%">
          <el-row :gutter="20" style="width: 400px; justify-content: flex-end">
            <el-card style="background-color: #000">
              <el-empty description="暂无选中元素" v-show="!activeTab"></el-empty>
              <!-- 小车配置 -->
              <el-form
                label-position="left"
                label-width="80px"
                style="padding: 10px"
                v-show="activeTab === EType.Car.alias"
              >
                <el-form-item label="索引">
                  <div style="display: flex; gap: 6px">
                    <el-input-number size="small" :min="0" v-model="config.car.range[0]" />
                    <el-input-number size="small" :min="0" v-model="config.car.range[1]" />
                  </div>
                </el-form-item>
                <el-form-item label="宽度">
                  <el-input-number size="small" :min="0" v-model="config.car.width" />
                </el-form-item>
                <el-form-item label="高度">
                  <el-input-number size="small" :min="0" v-model="config.car.height" />
                </el-form-item>
                <el-form-item label="弯曲角度">
                  <el-input-number size="small" v-model="config.car.totalAngle" />
                </el-form-item>
                <el-form-item label="旋转弧度">
                  <el-input-number size="small" v-model="config.car.radian" />
                </el-form-item>
                <el-form-item label="旋转角度">
                  <el-input-number size="small" v-model="config.car.rotate" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.car.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.car"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <!-- 格口配置 -->
              <el-form
                v-show="activeTab === EType.Export.alias"
                label-position="left"
                label-width="80px"
                style="padding: 10px"
              >
                <el-form-item label="索引">
                  <div style="display: flex; gap: 6px">
                    <el-input-number size="small" :min="0" v-model="config.export.range[0]" />
                    <el-input-number size="small" :min="0" v-model="config.export.range[1]" />
                  </div>
                </el-form-item>
                <el-form-item label="宽度">
                  <el-input-number size="small" :min="0" v-model="config.export.width" />
                </el-form-item>
                <el-form-item label="高度">
                  <el-input-number size="small" :min="0" v-model="config.export.height" />
                </el-form-item>
                <el-form-item label="弯曲角度">
                  <el-input-number size="small" v-model="config.export.totalAngle" />
                </el-form-item>
                <el-form-item label="旋转弧度">
                  <el-input-number size="small" v-model="config.export.radian" />
                </el-form-item>
                <el-form-item label="旋转角度">
                  <el-input-number size="small" v-model="config.export.rotate" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.export.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.export"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <!-- 方块（电机）配置 -->
              <el-form v-show="activeTab === EType.Electrical.alias">
                <el-form-item label="索引">
                  <el-input-number size="small" v-model="config.electrical.index" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.electrical.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.electrical"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <!-- 供包台 -->
              <el-form v-show="activeTab === EType.Entrance.alias">
                <el-form-item label="翻转">
                  <el-switch
                    v-model="config.entrance.flip"
                    :inactive-value="false"
                    :active-value="true"
                  />
                </el-form-item>
                <el-form-item label="索引">
                  <el-input-number size="small" v-model="config.entrance.index" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.entrance.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.entrance"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <!-- 直线 -->
              <div v-show="activeTab === EType.RoundEdge.alias">
                <el-form>
                  <el-row
                    style="color: rgba(255, 255, 255, 0.6); font-size: 12px; margin-bottom: 12px"
                  >
                    <span>双击圆点可删除路径点，按住ctrl单击边可添加路径点</span>
                  </el-row>
                  <el-form-item label="线条宽度">
                    <el-input-number size="small" v-model="config.roundEdge.strokeWidth" />
                  </el-form-item>
                  <el-form-item label="索引">
                    <el-input-number size="small" v-model="config.roundEdge.index" />
                  </el-form-item>
                  <el-form-item label="分组">
                    <el-select v-model="config.roundEdge.tag" placeholder="请选择">
                      <el-option
                        v-for="item in ETagOptions.roundEdge"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 曲线-->
              <div v-show="activeTab === EType.SmoothEdge.alias">
                <el-form>
                  <el-row
                    style="color: rgba(255, 255, 255, 0.6); font-size: 12px; margin-bottom: 12px"
                  >
                    <span>双击圆点可删除路径点，按住ctrl单击边可添加路径点</span>
                  </el-row>
                  <el-form-item label="线条宽度">
                    <el-input-number size="small" v-model="config.smoothEdge.strokeWidth" />
                  </el-form-item>
                  <el-form-item label="索引">
                    <el-input-number size="small" v-model="config.smoothEdge.index" />
                  </el-form-item>
                  <el-form-item label="分组">
                    <el-select v-model="config.smoothEdge.tag" placeholder="请选择">
                      <el-option
                        v-for="item in ETagOptions.smoothEdge"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 线条 -->
              <el-form
                label-position="left"
                label-width="80px"
                style="padding: 10px"
                v-show="activeTab === EType.Line.alias"
              >
                <el-form-item label="颜色">
                  <el-color-picker v-model="config.line.fill"></el-color-picker>
                </el-form-item>
                <el-form-item label="索引">
                  <el-input-number size="small" v-model="config.line.index" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.line.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.line"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <!-- 文字 -->
              <el-form
                v-show="activeTab === EType.Document.alias"
                label-position="left"
                label-width="80px"
                style="padding: 10px"
              >
                <el-form-item label="内容">
                  <el-input v-model="config.document.content" range />
                </el-form-item>
                <el-form-item label="字体大小">
                  <el-input-number v-model="config.document.size" />
                </el-form-item>
                <el-form-item label="索引">
                  <el-input-number size="small" v-model="config.document.index" />
                </el-form-item>
                <el-form-item label="分组">
                  <el-select v-model="config.document.tag" placeholder="请选择">
                    <el-option
                      v-for="item in ETagOptions.document"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-card>
          </el-row>
          <el-row style="width: 400px; justify-content: flex-end; margin-top: 10px">
            <el-popconfirm title="确认清空吗" @confirm="reset">
              <el-button slot="reference">清空</el-button>
            </el-popconfirm>

            <el-popconfirm title="确认删除选中吗" @confirm="clearSelect">
              <el-button slot="reference">删除选中</el-button>
            </el-popconfirm>
            <el-button @click="saveTo()">保存</el-button>
            <el-button @click="output">输出数据</el-button>
          </el-row>
        </div>
        <div style="position: absolute; right: 2%; bottom: 5%" class="legend">
          <el-row style="color: rgba(255, 255, 255, 0.6); padding: 5px; align-items: center">
            <div
              style="
                box-shadow: 0 0 3px 0px #7efffc;
                text-align: center;
                cursor: pointer;
                padding: 0 10px;
              "
              @click="graph.zoomToFit({ maxScale: 1 })"
            >
              点击居中
            </div>
          </el-row>
          <el-row style="color: rgba(255, 255, 255, 0.6); padding: 5px; align-items: center">
            <div style="display: flex; flex-wrap: wrap; width: 130px; gap: 4px">
              <code>Ctrl + A</code>全选
              <code>Ctrl + C</code>复制 <code>Ctrl + X</code>剪切 <code>Ctrl + V</code>粘贴
              <code>Ctrl + Z</code>撤销 <code>按住右键</code>拖动画布
              <code>Shift + 左键</code>选择区域
            </div>
          </el-row>
        </div>
      </div>
    </div>
  </ScaleScreen>
</template>
<script>
import { createGraph, getGraphScale, setGraphScale } from './createGraph/graph';
import {
  EType,
  ETagOptions,
  genDefaultConfig,
  createRoundEdge,
  createDocument,
  mouseClickCreateRoundEdge,
  createAttrsAndMarkup,
  createAttrsAndMarkupForEntrance,
  createAttrsAndMarkupForElectrical,
} from './createGraph/config';
import createStencil from './createGraph/stencil';
import graphEvent from './createGraph/event';
import ScaleScreen from '../scale-screen/scale-screen.vue';

export default {
  data() {
    return {
      EType,
      ETagOptions,
      selectedCell: null,
      editing: true,
      activeTab: null,
      config: genDefaultConfig(),
      graph: null,
      btn: true,
      edit: true,
      graphCurrentData: [],
    };
  },
  components: {
    ScaleScreen,
  },
  async mounted() {
    const graph = createGraph('container', true);
    createStencil(graph, this);
    graphEvent(graph, this);

    this.graph = graph;
    this.graph.drawBackground({
      position: 'center',
      size: '100% 100%',
    });

    // 加载数据
    await this.getData();

  },
  methods: {
    reset() {
      this.graph.clearCells();
    },
    async getData() {
      try {
        const res = await fetch('/line/viewdata/initViewData');
        const { data } = await res.json();
        this.graph.fromJSON(JSON.parse(data.data));
        setGraphScale(this.graph, {...res});
        return data
      } catch (error) {
        console.error('获取数据时出错:', error);
      }
    },
    clearSelect(_val) {
      // 获取当前选中的节点
      const selectedCells = this.graph.getSelectedCells(); // 获取所有选中的单元格（节点/边）

      // 检查是否有选中节点并删除
      if (selectedCells.length > 0) {
        selectedCells.forEach((cell) => {
          this.graph.removeCell(cell); // 删除节点
        });
      }
    },
    output() {
      // const cells = this.graph.getCells();
      // cells.forEach((cell) => {
      //   if (cell.isEdge()) {
      //     cell.attr('line/targetMarker', null);
      //     cell.prop('tools', null);
      //   }
      // });

      const data = {
        // 小车
        car: [
          { color: 'red', index: 0, remark: 'rwq', showName: 0, tag: '1' },
          { color: '#ff0000', index: 1, remark: '', showName: 1, tag: '2' },
          { color: '#31dca0', index: 2, remark: '', showName: 2, tag: '3' },
          { color: '#31dca0', index: 3, remark: '', showName: 3, tag: '4' },
          { color: '#31dca0', index: 4, remark: '', showName: 4, tag: '5' },
          { color: '#ff0000', index: 5, remark: '', showName: 5, tag: '6' },
          { color: '#31dca0', index: 6, remark: '', showName: 6, tag: '7' },
          { color: '#31dca0', index: 7, remark: '', showName: 7, tag: '8' },
          { color: '#31dca0', index: 8, remark: '', showName: 8, tag: '9' },
          { color: '#31dca0', index: 9, remark: '', showName: 9, tag: '10' },
          { color: 'red', index: 10, remark: '试试', showName: 10, tag: '11' },
        ],
        // 格口
        export: [
          { color: '#ff0000', index: 0, remark: '', showName: '0' },
          { color: '#ff0000', index: 1, remark: '', showName: '1' },
          { color: '#037dd3', index: 2, remark: '', showName: '2' },
        ],
        // 供包台
        entrance: [
          { color: '#ff0000', index: 0, remark: '', showName: '0', tag: 'entrance1' },
          { color: 'red', index: 1, remark: '', showName: '1', tag: 'entrance1' },
          { color: 'green', index: 2, remark: '', showName: '2', tag: 'entrance1' },
        ],
        // 急停
        // alarm: [
        //   { color: '#66CD00', index: 0, remark: '', showName: '0' },
        //   { color: '#66CD00', index: 1, remark: '', showName: '1' },
        //   { color: '#66CD00', index: 2, remark: '', showName: '2' },
        //   { color: '#66CD00', index: 3, remark: '', showName: '3' },
        // ],
        // 电机
        electrical: [
          { color: '#ff0000', index: 0, remark: '', showName: '0', tag: 'electrical1' },
          { color: '#31dca0', index: 1, remark: '', showName: '1', tag: 'electrical1' },
          { color: '#31dca0', index: 2, remark: '', showName: '2', tag: 'electrical1' },
          { color: '#31dca0', index: 3, remark: '', showName: '3', tag: 'electrical1' },
        ],
      };
      const graphData = this.graph.getCells();
      const carData = graphData.filter((item) => item.data?.type === EType.Car.alias);
      const exportData = graphData.filter((item) => item.data?.type === EType.Export.alias);
      const entranceData = graphData.filter((item) => item.data?.type === EType.Entrance.alias);
      const electricalData = graphData.filter((item) => item.data?.type === EType.Electrical.alias);

      Object.keys(data).forEach((key) => {
        for (let item of data[key]) {
          const { color, showName, tag, remark } = item;
          // 处理小车
          if (key === EType.Car.alias) {
            carData.forEach((cell) => {
              // 这里-1是因为graph_event那里会导致拐角少了一个，有时间再排查,这里-1在赋值处已经做了处理
              const selectorBody = showName == 0 ? 'body' : `body${showName - 1}`;
              const selectorText = showName == 0 ? 'text' : `text${showName - 1}`;
              const attrs = cell.getAttrs();
              if (cell.prop('data')?.tag === tag) {
                attrs[selectorBody] && cell.attr(`${selectorBody}/fill`, color);
                attrs[selectorBody] && cell.attr(`${selectorText}/text`, remark);
              }
            });
          }

          // 处理格口
          if (key === EType.Export.alias) {
            exportData.forEach((cell) => {
              const selectorBody = showName == 0 ? 'body' : `body${showName - 1}`;
              const selectorText = showName == 0 ? 'text' : `text${showName - 1}`;
              const attrs = cell.getAttrs();
              if (cell.prop('data')?.tag === tag) {
                attrs[selectorBody] && cell.attr(`${selectorBody}/fill`, color);
                attrs[selectorBody] && cell.attr(`${selectorText}/text`, remark);
              }
            });
          }

          // 处理供包台
          if (key === EType.Entrance.alias) {
            entranceData.forEach((cell) => {
              const { tag: curTag, index } = cell.prop('data');
              if (curTag === tag && index == showName) {
                cell.attr(`body1/fill`, color);
                cell.attr(`polygon/fill`, color);
                cell.attr(`body/fill`, color);

                cell.attr(`text/text`, remark);
              }
            });
          }

          // 处理电机
          if (key === EType.Electrical.alias) {
            electricalData.forEach((cell) => {
              const { tag: curTag, index } = cell.prop('data');
              if (curTag === tag && index == showName) {
                cell.attr(`body/fill`, color);
                cell.attr(`text/text`, remark);
              }
            });
          }
        }
      });
    },
    async saveTo() {
      if (JSON.stringify(this.graph.toJSON().cells) === '[]') {
        return this.$message.warning({
          content: '当前没有图表数据',
          placement: 'center',
        });
      }

      const saveConfigDataValue = async (value) => {
        console.log({...value})
        try {
          const response = await fetch('/line/viewdata/updateViewDataValue', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },

            body: JSON.stringify({...value}),
          });
          const res = await response.json();
          this.$message.success({
            content: res.msg,
            placement: 'center',
          });
        } catch (error) {
          console.error('Error saving config data:', error);
          this.$message.error({
            content: '保存图表数据时出错',
            placement: 'center',
          });
        }
      };



      await saveConfigDataValue(this.graph.toJSON());

      const { scaleX,scaleY,translateX,translateY} = getGraphScale(this.graph)
      const saveConfigData = async (key, value) => {
        try {
          const params = new URLSearchParams({ key, value }).toString();
          const response = await fetch(`/line/viewdata/updateViewData?${params}`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
          });
          const res = await response.json();
          this.$message.success({
            content: res.msg,
            placement: 'center',
          });
        } catch (error) {
          console.error('Error saving config data:', error);
          this.$message.error({
            content: '保存图表数据时出错',
            placement: 'center',
          });
        }
      }
      //
      await saveConfigData('VIEW_BASE_SCALESX', scaleX);
      await saveConfigData('VIEW_BASE_SCALESY', scaleY);
      await saveConfigData('VIEW_BASE_TRANSLATEX', translateX);
      await saveConfigData('VIEW_BASE_TRANSLATEY', translateY);

    }
  },
  watch: {
    // 根据配置修改节点属性
    config: {
      handler(val) {
        if (!this.selectedCell) return;
        const { id } = this.selectedCell;
        const res = this.graph.getCellById(id);
        if (!res?.data) return;
        const {
          data: { type },
        } = res;
        if (type === EType.Car.alias) {
          const {
            range: [start, end],
            rotate,
            totalAngle,
            radian,
            tag,
            width,
            height,
          } = val.car;
          createAttrsAndMarkup(this.selectedCell, {
            ...val[type],
            width,
            height,
            start,
            end,
          });
        }
        // 格口
        else if (type === EType.Export.alias) {
          const {
            range: [start, end],
            totalAngle,
            rotate,
            radian,
            tag,
            width,
            height,
          } = val.export;

          createAttrsAndMarkup(this.selectedCell, {
            ...val[type],
            width,
            height,
            start,
            end,
            fill: '#037dd3',
          });
        }
        // 供包台
        else if (type === EType.Entrance.alias) {
          const { flip, index, tag } = val.entrance;
          if (flip) this.selectedCell.attr('polygon/transform', `scale(-1,1) translate(-50, 0)`);
          else this.selectedCell.attr('polygon/transform', `scale(1,1) translate(0, 0)`);
          createAttrsAndMarkupForEntrance(this.selectedCell, {
            ...val[type],
          });

          // 置底
          this.selectedCell.toBack();
        }
        // 电机
        else if (type === EType.Electrical.alias) {
          const { index, tag } = val.electrical;
          console.log(val.electrical);
          createAttrsAndMarkupForElectrical(this.selectedCell, {
            ...val[type],
          });
        }
        // 文字
        else if (type === EType.Document.alias) {
          const { content, index, tag, size } = val.document;
          createDocument(this.selectedCell, {
            ...val[type],
          });
        }
        // 线条
        else if (type === EType.Line.alias) {
          const { fill, height } = val.line;
          this.selectedCell.attr('text/text', '');
          this.selectedCell.attr('body/fill', fill);
        }
        // 直线
        else if (type === EType.RoundEdge.alias) {
          const { strokeWidth, index, tag } = val.roundEdge;
          this.selectedCell.attr('line/strokeWidth', strokeWidth);
          this.selectedCell.prop('data', {
            ...this.selectedCell.prop('data'),
            strokeWidth,
            index,
            tag,
          });
        }
        // 曲线
        else if (type === EType.SmoothEdge.alias) {
          const { strokeWidth, index, tag } = val.smoothEdge;

          this.selectedCell.attr('line/strokeWidth', strokeWidth);
          this.selectedCell.prop('data', {
            ...this.selectedCell.prop('data'),
            strokeWidth,
            index,
            tag,
          });
        }
      },
      deep: true,
    },
  },
};
</script>
<style scoped lang="less">
#container {
  transition: all 0.5s;
}

.hidden {
  transform: translateX(-300px);
  transition: transform 1s;
}

#screen {
  background-image: url('~@/assets/images/screen/background.png');
  background-size: 100% 100%;
}

#flow_man {
  overflow: hidden;

  .legend {
    background-color: #152242;
    padding: 10px 30px;
    padding-bottom: 0;
    opacity: 0.8;
    box-shadow: 0 0 5px 1px #152242;
  }

  .legend div {
    font-size: 12px;
  }

  .legend span {
    position: relative;
    width: 40px;
    height: 2px;
    background-color: #83fffe;
    margin-right: 15px;
  }

  .legend span::before {
    content: '';
    position: absolute;
    right: 35%;
    top: -4px;
    border: 5px solid #83fffe;
    border-radius: 50%;
  }

  .legend .danger {
    background-color: #ffc97a;
  }

  .legend .danger::before {
    border: 5px solid #ffc97a;
  }

  .legend .error {
    background-color: #dd5b5b;
  }

  .legend .error::before {
    border: 5px solid #dd5b5b;
  }

  /* stencil */
  #stencil {
    position: absolute;
    width: 300px;
    height: 99%;
    z-index: 1;
    top: 5px;
  }

  :deep(.x6-widget-stencil) {
    /* display: none; */
    background: none !important;
  }

  /* 设备图例 */
  :deep(.x6-widget-stencil-title) {
    display: none;
  }

  :deep(.x6-widget-stencil-group-title) {
    padding-left: 44px !important;
    // margin: 23px 4px;
    margin-bottom: 0;
    width: 98% !important;
    font-size: 14px !important;
    color: #fff !important;
    background: url('~@/assets/images/screen/title.png') no-repeat !important;
  }

  :deep(.x6-widget-stencil-group-title::before) {
    /* background-color: #000!important; */
    background-image: none !important;
  }

  :deep(.x6-widget-stencil-content) {
    top: 0 !important;
    transition: all 0.4s;
    background-color: rgba(17, 34, 69, 0.6);
  }

  :deep(.x6-graph) {
    padding-bottom: 10px;
    box-sizing: content-box;
  }

  :deep(.x6-widget-stencil-group.collapsed) {
    max-height: 60px !important;
  }

  code {
    background-color: #e9e9e9;
    color: #000;
    border: 3px solid #e9e9e9;
    border-radius: 5px;
    margin-right: 5px;
  }
}

:deep(.el-tabs__item) {
  color: #ffffff;
}

:deep(.el-card__body) {
  padding-bottom: 0;
}
:deep(.x6-graph.x6-graph-pannable) {
  cursor: default;
}
</style>
